import request from '@/utils/request'
import axios from 'axios'

/**
 * 获取oss上传policy
 */
export function getPolicy() {
  return request({
    url: '/oss/getPolicy',
    method: 'get'
  })
}
/**
 * 上传文件
 * @param 文件名 fileName
 * @param 文件对象 file
 */
export function upload(fileName, file) {
  fileName = new Date().getTime() + getSuffix(fileName)
  return new Promise((resolve, reject) => {
    getPolicy()
      .then(res => {
        let formData = new FormData()
        //注意formData里append添加的键的大小写
        formData.append('key', res.dir + fileName) //存储在oss的文件路径
        formData.append('OSSAccessKeyId', res.accessid) //accessKeyId
        formData.append('policy', res.policy) //policy
        formData.append('Signature', res.signature) //签名
        //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
        formData.append('file', file)
        let url = res.host
        let fileUrl = url + '/' + res.dir + fileName
        let service = axios.create({
          // 超时
          timeout: 10000
        })
        service({
          url: url,
          method: 'post',
          data: formData,
          contentType: 'multipart/form-data'
        }).then(res => {
          console.log(res)
          console.log('文件地址:', fileUrl)
          resolve(fileUrl)
        })
      })
      .catch(err => {
        reject()
      })
  })
}

function getSuffix(fileName) {
  let pos = fileName.lastIndexOf('.')
  let suffix = ''
  if (pos != -1) {
    suffix = fileName.substring(pos)
  }
  return suffix
}
